package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.service.CourseTeacherService;
import com.xuecheng.exception.XueChengPlusException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.cert.X509Certificate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 杨振华
 * @since 2023/9/24
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    /**
     * 查找教师
     * @param courseId
     * @return {@link List}<{@link CourseTeacher}>
     */
    @Override
    public List<CourseTeacher> queryTeachers(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CourseTeacher::getCourseId, courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        return courseTeachers;
    }

    /**
     * 新增或修改教师
     * @param courseTeacher
     * @return {@link CourseTeacher}
     */
    @Override
    public CourseTeacher saveOrUpdate(CourseTeacher courseTeacher) {
        Long id = courseTeacher.getId();
        if (id == null) {
            // 则为新增教师
            CourseTeacher teacher = new CourseTeacher();
            BeanUtils.copyProperties(courseTeacher, teacher);
            teacher.setCreateDate(LocalDateTime.now());
            int insert = courseTeacherMapper.insert(courseTeacher);
            if (insert <= 0) {
                XueChengPlusException.cast("新增教师失败！");
            }
        }else {
            CourseTeacher teacher = courseTeacherMapper.selectById(courseTeacher.getId());
            BeanUtils.copyProperties(courseTeacher, teacher);
            int update = courseTeacherMapper.updateById(teacher);
            if (update <= 0) {
                XueChengPlusException.cast("修改教师失败！");
            }
        }
        return courseTeacherMapper.selectById(id);
    }

    /**
     * 删除教师
     * @param courseId
     * @param teacherId
     */
    @Override
    public void deleteTeacher(Long courseId, Long teacherId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CourseTeacher::getCourseId, courseId)
                .eq(CourseTeacher::getId, teacherId);
        int delete = courseTeacherMapper.delete(queryWrapper);
        if (delete <= 0) {
            XueChengPlusException.cast("删除教师失败");
        }
    }
}
